//获取用户操作
var pattern = new RegExp(/\?Code=(\S*)/g);
var idx = pattern.exec(window.location.href);
var _Level, PicCode, PictureName, jgData02, jgData03, jgData04, _Data, order, Father='', Father_N='', Content_PC = '', Content_M = '';

//  var grid03 = $('#jgTable03'),
//  grid04 = $('#jgTable04'),
var _grid = $('#_jgTable'),
    ItemCode = $("input[data-field='ItemCode']"),
    Name = $("input[data-field='ItemName']"),
    Brand = $("input[data-field='ItemBrand']"),
    FullName = $("input[data-field='ItemFullName']");

$(function(){
    
    // requestSort(0, 1);
    // Category1.on('change', function(){
    //     requestSort($(this).val(), 2);
    //     Category2.trigger('change');
    // });
    // Category2.on('change', function(){
    //     requestSort($(this).val(), 3);
    // });
    // Category1.trigger('change');

    request66();
    requestAjax();
    // gridInit03();
    // gridInit04();
    _gridInit();
    $('.u_pictures .u_item, .u_pictures .u_add_item').on('click', addPictures);
    // $("li[data-opt='add']").on('click', addCode);
    $("li[data-opt='back']").on('click', back);
    setContent('iframePC', Content_PC);
    // setContent('iframeM', Content_M);
    $('#BrandBtn').on('click', addDetailCode);
    $("#js_submit, li[data-opt='save']").on("click", saveSubmit);
    $('.item_close').on('click', function(){
        $('.u_panes .u_item').html('<a href="javascript:0;"></a>');
    })
    $('.modal-data').draggable();

});

// function requestSort(PCode, Level){
//     _Level = Level;
//     var postData01 = Object.create(postData);
//     postData01.Method = 'Q';
//     postData01.Content = {
//         PCode: PCode,
//         Level: Level
//     };
//     $.ajax({
//         async: false,
//         type: 'post',
//         url: mdmPath + '/MDM0003/MDM000304',
//         data: postData01,
//         dataType: 'json',
//         success: function (re) {
//             if (re.Status == 200) {
//                 loadSort(re);
//             } else {
//                 myAlert(re.Message);
//             }
//         }
//     });
// }
// function loadSort(re){
//     var arr = re.Content.rows,
//         options = '';
//     arr.forEach(function(v,i,a){
//         options += '<option value="'+v.Code+'">'+v.Name+'</option>'
//     });
//     //console.log(options)
//     switch(_Level){
//         case 1:
//             $('#ItemCategory1').html(options);
//         break;
//         case 2:
//             $('#ItemCategory2').html(options);
//         break;
//         case 3:
//             $('#ItemCategory3').html(options);
//         break;
//     }
// }

function request66(){ //MDM0066/MDM006602
  var _postData = Object.create(postData);
  _postData.Method = 'Q';
  _postData.page = 1;
  _postData.rows = 10000;
  _postData.sidx = "Code";
  _postData.sord = "Asc"
  _postData.Content = {
    SearchText: ''
  }
  $.ajax({
    async: false,
    type: 'post', 
    url: mdmPath + '/MDM0066/MDM006602',
    data: _postData,
    dataType: 'json',
    success: function (re) {
      load66(re);
    }
  });  
}
function load66(re){
  var data = re.Content.rows;
  var html = '';
  data.forEach(function(v,i,a){
    html += '<option value="'+v.Code+'">'+v.Name+'</option>'
  })
  $('#m_Select').html(html)
}

function requestAjax(){ //MDM000403
    if(idx){
        var _postData = Object.create(postData);    //请求头
        _postData.Method = 'Q';
        _postData.Content = {
            "Code": idx[1]
        }
        $.ajax({
            async: false,
            type: 'post', 
            url: mdmPath + '/MDM0004/MDM000403',
            data: _postData,
            dataType: 'json',
            success: function (re) {
                if (re.Status == 200) {
                    loadAjax(re);
                } else if (re.Status == -999) {
                    alert_QX($('body'), re.Message);
                } else {
                    myAlert(re.Message);
                }
            }
        });
    }
}
function loadAjax(re){
    if(re.Status==200){
        ItemCode.val(re.Content.Code); //代码
        Name.val(re.Content.Name); //名称
        // Brand.val(re.Content.Brand); //品牌
        // FullName.val(re.Content.FullName); //全称
        // Category1.val(re.Content.Category1);  //一级分类
        // requestSort(Category1.val(), 2);
        // Category2.val(re.Content.Category2);  //二级分类
        // requestSort(Category2.val(), 3);
        // Category3.val(re.Content.Category3);  //三级分类
        Content_PC = re.Content.PCDetail; //PC详情
        // Content_M = re.Content.MobileDetail;   //Mobile详情
        if(re.Content.PicturePath){  //主图
            PicCode = re.Content.PicCode;
            PicName = re.Content.PicName;
            $(".u_pictures .u_item").html('<img src="'+PicAddress+re.Content.PicturePath+'">');
        }
        $("#createDate").val(re.Content.CreateDate);    //
        $("#updateDate").val(re.Content.UpdateDate);    //
        $("#createUser").val(re.Content.CreateUser);    //
        $("#updateUser").val(re.Content.UpdateUser);    //
        // jgData02 = re.Content.MDM000902;
        // jgData03 = re.Content.MDM000903;
        if(re.Content.ImgManger == 'Y'){
            $("#ImgManger").prop("checked", true);
        }else if(re.Content.ImgManger == 'N'){
            $("#ImgManger").prop("checked", false);
        }
        if(re.Content.DetailManger == 'Y'){
            $("#DetailManger").prop("checked", true);
        }else if(re.Content.DetailManger == 'N'){
            $("#DetailManger").prop("checked", false);
        }
        jgData04 = re.Content.MDM000404;
        _Data = re.Content.MDM000408R;
        order = _Data.length;
        if(jgData04){
            var html = '';
            jgData04.forEach(function(v,i,a){
                html += '<li class="u_add_item">'+
                    '<img src="'+PicAddress+v.Piclocation+'" alt="">'+
                    '<i class="fa fa-times fa-2x u_close"></i>'+
                    '<p class="u_desc">'+v.PicName+'</p>'+
                '</li>'
            });
            $('li[data-tab="detailPC"] .u_add_item').before(html);
            var count = jgData04.length;
            console.log(count)
            $('.u_add_item .u_close').unbind('click').bind('click', function(){
                $(this).parents().filter('.u_add_item').remove();
                count > 4 &&(count = 4);
                count --;
            });
        }
    }else{
        myAlert(re.Message);
    }
}

// function picFormatter(cellvalue, options, rowdata){
//     if(rowdata.Piclocation){
//         return '<img src="'+PicAddress+rowdata.Piclocation+'"  style="width:100px">';
//     }else{
//         return '';
//     }
// }
function alarmFormatter(cellvalue, options, rowdata){
    var grid = $(this);
    if(JSON.stringify(rowdata)!=='{}'){
        cellvalue = '<a href="javascript:0" opt-data="'+grid[0].id+'_delete" title="删除"><i class="fa fa-trash-o"></i></a>';
    }else{
        cellvalue = '';
    }
    return cellvalue;
}
// function gridInit03(){
//     var gridData03 = Object.create(gridData);
//     gridData03.grid = $('#jgTable03');
//     //gridData03.pager = $('#jgPager03');
//     gridData03.datatype = "local";
//     gridData03.rowNum = 100;
//     gridData03.colModel = [
//         {label:'代码', name:'PropertyCode'},
//         {label:'名称', name:'PropertyName'},
//         {label:'操作', name:'Options', width:60, formatter:alarmFormatter, sortable:false}
//     ];
//     gridData03.beforeRequest = function(){
//         gridData03.grid.jqGrid("setGridParam", {
//             data : jgData03
//         });
//     };
//     gridInit(gridData03);
// }
// function gridInit04(){
//     var gridData04 = Object.create(gridData);
//     gridData04.grid = $('#jgTable04');
//     //gridData04.pager = $('#jgPager04');
//     gridData04.datatype = "local";
//     gridData04.rowNum = 100;
//     gridData04.colModel = [
//         {label:'代码', name:'PicCode'},
//         {label:'名称', name:'PicName'},
//         {label:'图片', name:'Piclocation', formatter:picFormatter, sortable:false},
//         {label:'操作', name:'Options', width:60, formatter:alarmFormatter, sortable:false}
//     ];
//     gridData04.beforeRequest = function(){
//         gridData04.grid.jqGrid("setGridParam", {
//             data : jgData04
//         });
//     };
//     gridInit(gridData04);
// }
function _gridInit(){
    var _gridData = Object.create(gridData);
    _gridData.grid = $('#_jgTable');
    // _gridData.pager = $('#_jgPager');
    _gridData.datatype = "local";
    _gridData.rowNum = 10000;
    _gridData.colModel = [
        {label:'代码', name:'Code', hidden:true},
        {label:'排序号', name:'OrderById', hidden:true},
        {label:'分类代码', name:'DetailCode', hidden:true},
        {label:'分类名称', name:'DetailName', sortable:false},
        {label:'详情', name:'Detail', hidden:true},
        {label:'操作', name:'Options', width:60, formatter:alarmFormatter, sortable:false}
    ];
    _gridData.beforeRequest = function(){
        _gridData.grid.jqGrid("setGridParam", {
            data : _Data
        });
    };
    _gridData.loadComplete = function(xhr){
        //var rowData = _gridData.grid.jqGrid("getRowData");
        $('a[opt-data="_jgTable_delete"]').unbind('click').bind('click',function(){
            var rowId = $(this).parent().parent()[0].id;
            var delData = _grid.jqGrid("getRowData",rowId);
            _Data.forEach(function(v,i,a){
                v.DetailCode == delData.DetailCode && _Data.splice(i,1);
            });
            _gridData.grid.jqGrid("delRowData",rowId);
            console.log(_Data)
        });
    };
    _gridData.onSelectRow = function(rowid,status){
        var myEditor = document.getElementsByName("_iframe")[0].contentWindow.document.getElementById('editor');
        console.log(myEditor)
        var rowData = _grid.jqGrid('getRowData', rowid);
        Father = rowData.DetailCode;
        Father_N = rowData.DetailName;
        $('#e_save').unbind('click').bind('click', function(){
            _Data.forEach(function(v,i,a){
                console.info(v.DetailCode == Father)
                v.DetailCode == Father && (_Data[i].Detail = getContent('_iframe'))
            })
            myAlert('本地保存成功')
        })
        // myEditor.onblur = function(){
        //     console.log('失去')
        //     _Data.forEach(function(v,i,a){
        //         v.DetailCode == Father && (_Data[i].Detail = getContent('_iframe'))
        //     })
        // }
        var Content = rowData.Detail;
        console.log(Content)
        //myEditor.innerHTML = Content;
        var _iframe = document.getElementsByName("_iframe")[0].contentWindow;
        _iframe.setContent(Content);
        $('h3.u_title').eq(2).html(`<i class="fa fa-picture-o"></i>&nbsp;产品详情&nbsp;`+Father_N)
        _grid.trigger("reloadGrid");
    };
    gridInit(_gridData);  
}

//Options
// function addCode(){
//     window.open('MDM000403.html', '_blank');  
// }
function back(){
    window.open('MDM000401.html', '_self');
}
function addDetailCode(){
    $('#modal1').removeClass('hidden');
    $('#submit1').unbind('click').bind('click', function(){
        _Data.push({
            Code:idx[1],
            OrderById:++order,
            DetailCode:$('#m_Select').find('option:selected').val(), 
            DetailName:$('#m_Select').find('option:selected').text()
        });
        _Data = _Data.unique('DetailCode');
        _grid.trigger("reloadGrid");
        $('#modal1').addClass('hidden');
    });
}

function saveSubmit(){  //MDM000909
    var PictureCode = "", PictureLocation = "";
    if($("li[data-tab='detailPC'] .u_item img").length>0){  //如果img存在，获取img地址
        var src_P = $("li[data-tab='detailPC'] .u_item img")[0].src;
        if(src_P.indexOf(PicAddress)!=-1){
            PictureLocation = src_P.slice(PicAddress.length);
            var tempArr = PictureLocation.split('/');
            var tempCode = tempArr[tempArr.length-1];
            PictureCode = tempCode.split('.')[0];
        }
    }
    var PicCode= "", PicName = "", MDM000404 = [];
    var src_Ps = $("li[data-tab='detailPC'] .u_add_item").find("img");
    if(src_Ps.length>0){
        var txt_Ps = $("li[data-tab='detailPC'] .u_add_item").find("p");
        for(var i=0;i<src_Ps.length;i++){
            var Piclocation = src_Ps[i].src.slice(PicAddress.length);
            var tempArr = Piclocation.split('/');
            var tempCode = tempArr[tempArr.length-1];
            PicCode = tempCode.split('.')[0];
            PicName = txt_Ps.eq(i).html();
            MDM000404.push({Code:ItemCode.val(),LineID:i,OrderById:i,PicCode:PicCode,PicName:PicName,Piclocation:Piclocation});
        }
    }
    if($("#ImgManger").prop("checked")){
        var ImgManger = 'Y'
    }else{
        var ImgManger = 'N'
    }
    if($("#DetailManger").prop("checked")){
        var DetailManger = 'Y'
    }else{
        var DetailManger = 'N'
    }
    var requestData = {
        Content: {
            ImgManger: ImgManger,
            DetailManger: DetailManger,
            Code: ItemCode.val(),    
            PCDetail: getContent('iframePC'),
            // MobileDetail: getContent('iframeM'),
            PicCode: PictureCode,
            PicturePath: PictureLocation,
            PicName: PictureName,
            loMDM000404: MDM000404,
            loMDM000408: _Data
        },
    }
    // if(idx){
        requestData.Method = 'U'
    // }else{
    //     requestData.Method = 'A'
    // }
    for(i in postData){
        requestData[i] = postData[i]
    }
    console.log(requestData);
    $.ajax({
        type: "post",
        url: mdmPath + '/MDM0004/MDM000411',
        data: requestData,
        dataType: "json",
        success: function(re) {
            if(re.Status==200){
                myAlert('保存成功')
            }else{
                myAlert(re.Message)
            }
        }
    });
}

//Styles
function gridSize(){ 
    // grid03.setGridWidth($('.u_pane_active').width());
    // grid04.setGridWidth($('.u_pane_active').width());
}


